<?php
// +----------------------------------------------------------------------
// | OneChat
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.tealun.com
// +----------------------------------------------------------------------
// | Author: Tealun Du <tealun@tealun.com> <http://www.tealun.com>
// +----------------------------------------------------------------------
namespace Wechat\Event;

use Wechat\Model\TchatClientModel;

/**
 * 客户图片类型消息处理类
 */
class ImageEvent extends BaseEvent {

    /**
     * 对图片类型消息进行处理
     *
     * @param $openId  客户openid
     * @param $mediaId 图片ID
     */
    public function imageHandle($openId , $mediaId) {
        $content = "( ＾-＾)っ您的图片收到啦\n";

        //认证判断
        if ( check_wechat_rz() === true ) {

            //下载图片
            $fileInfo = download_wechat_media($mediaId);

            $filePath = CLIENT_PHOTO . date('Ym' , time()) . "/";
            $fileName = time() . "-" . rand(100 , 999) . ".jpg";

            //存储图片，并保存到对应表中
            $picId = save_wechat_media($filePath , $fileName , $fileInfo["body"]);
            if(!$picId){
                $content = "( @_@)っ但是多啦A梦好像罢工了，没有收进它的口袋。";
            }else{
                $Client = new TchatClientModel();
                /* 将图片存储到数据库中，并与微信客户表中的客户ID关联*/
                $clientId = $Client->getIdByOpenid($openId);
                $data = array(
                    'client_id' => $clientId ,
                    'photo' => $filePath . $fileName ,
                    'create_time' => time() ,
                );
                $picId = M('Tchat_client_photo')->data($data)->add();
                $content .= "图片编号：Wp-".$picId.'\n';
                $filePath = str_replace('./' , '/' , $filePath);
                $content .= "<a href='http://" . $_SERVER["HTTP_HOST"] . $filePath . $fileName . "' >点击查看</a>";
            }
        }
        //回复客户内容
        return set_response_arr($content);
    }

}